package com.example.demo.service;

import org.flowable.cmmn.api.CmmnRuntimeService;
import org.flowable.cmmn.api.CmmnTaskService;
import org.flowable.cmmn.api.runtime.CaseInstance;
import org.flowable.cmmn.api.runtime.PlanItemInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * CMMN代理服务示例：客户投诉案例管理
 * 这个服务管理非结构化的案例处理流程
 */
@Service
public class CaseManagementService {

    @Autowired
    private CmmnRuntimeService cmmnRuntimeService;

    @Autowired
    private CmmnTaskService cmmnTaskService;

    /**
     * 启动客户投诉案例
     */
    public String startComplaintCase(String customerName, String complaintDescription, 
                                   String complaintHandler, String priority) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("customerName", customerName);
        variables.put("complaintDescription", complaintDescription);
        variables.put("complaintHandler", complaintHandler);
        variables.put("complaintPriority", priority);
        variables.put("complaintDate", System.currentTimeMillis());
        
        System.out.println("=== CMMN代理服务：启动投诉案例 ===");
        System.out.println("客户：" + customerName);
        System.out.println("投诉内容：" + complaintDescription);
        System.out.println("处理人：" + complaintHandler);
        System.out.println("优先级：" + priority);
        
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
                .caseDefinitionKey("customerComplaintCase")
                .variables(variables)
                .start();
        
        System.out.println("案例ID：" + caseInstance.getId());
        System.out.println("=====================================");
        
        return caseInstance.getId();
    }

    /**
     * 获取案例的当前任务
     */
    public List<Task> getCaseTasks(String caseInstanceId) {
        return cmmnTaskService.createTaskQuery()
                .caseInstanceId(caseInstanceId)
                .list();
    }

    /**
     * 完成案例任务
     */
    public void completeCaseTask(String taskId, Map<String, Object> variables) {
        System.out.println("=== CMMN代理服务：完成任务 ===");
        System.out.println("任务ID：" + taskId);
        System.out.println("任务变量：" + variables);
        
        cmmnTaskService.complete(taskId, variables);
        
        System.out.println("任务完成");
        System.out.println("========================");
    }

    /**
     * 获取案例的当前状态
     */
    public void getCaseStatus(String caseInstanceId) {
        System.out.println("=== CMMN代理服务：案例状态 ===");
        System.out.println("案例ID：" + caseInstanceId);
        
        // 获取案例实例
        CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceQuery()
                .caseInstanceId(caseInstanceId)
                .singleResult();
        
        if (caseInstance != null) {
            System.out.println("案例状态：进行中");
            System.out.println("案例变量：" + caseInstance.getCaseVariables());
        }
        
        // 获取当前活跃的计划项
        List<PlanItemInstance> activePlanItems = cmmnRuntimeService.createPlanItemInstanceQuery()
                .caseInstanceId(caseInstanceId)
                .planItemInstanceStateActive()
                .list();
        
        System.out.println("当前活跃任务：");
        for (PlanItemInstance planItem : activePlanItems) {
            System.out.println("- " + planItem.getName() + " (状态：" + planItem.getState() + ")");
        }
        
        // 获取已完成的里程碑
        List<PlanItemInstance> completedMilestones = cmmnRuntimeService.createPlanItemInstanceQuery()
                .caseInstanceId(caseInstanceId)
                .planItemInstanceStateCompleted()
                .list();
        
        System.out.println("已完成里程碑：");
        for (PlanItemInstance milestone : completedMilestones) {
            System.out.println("- " + milestone.getName());
        }
        
        System.out.println("========================");
    }

    /**
     * 手动触发案例阶段
     */
    public void triggerCaseStage(String caseInstanceId, String stageName) {
        System.out.println("=== CMMN代理服务：触发阶段 ===");
        System.out.println("案例ID：" + caseInstanceId);
        System.out.println("阶段：" + stageName);
        
        // 查找对应的阶段计划项
        List<PlanItemInstance> stageItems = cmmnRuntimeService.createPlanItemInstanceQuery()
                .caseInstanceId(caseInstanceId)
                .planItemInstanceName(stageName)
                .list();
        
        for (PlanItemInstance stageItem : stageItems) {
            if ("available".equals(stageItem.getState())) {
                // 手动启动阶段
                cmmnRuntimeService.startPlanItemInstance(stageItem.getId());
                System.out.println("阶段 " + stageName + " 已启动");
            } else {
                System.out.println("阶段 " + stageName + " 当前状态：" + stageItem.getState());
            }
        }
        
        System.out.println("========================");
    }

    /**
     * 获取案例历史
     */
    public void getCaseHistory(String caseInstanceId) {
        System.out.println("=== CMMN代理服务：案例历史 ===");
        System.out.println("案例ID：" + caseInstanceId);
        
        // 获取所有历史计划项
        List<PlanItemInstance> allPlanItems = cmmnRuntimeService.createPlanItemInstanceQuery()
                .caseInstanceId(caseInstanceId)
                .list();
        
        System.out.println("案例执行历史：");
        for (PlanItemInstance planItem : allPlanItems) {
            System.out.println("- " + planItem.getName() + 
                             " (类型：" + planItem.getPlanItemDefinitionType() + 
                             ", 状态：" + planItem.getState() + ")");
        }
        
        System.out.println("========================");
    }
}
